using B.S.BaseData.Domain;
using MediatR;
using SmartTracking.API.Write.Application.Commands.Purchasing.Eliminates;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Write.Application.CommandHandlers.Purchasing.Eliminates
{
    public class DeleteEliminateCommandHandler : IRequestHandler<DeleteEliminateCommand, ApiResult<int>>
    {

        private readonly IBaseRepository<Eliminate> eliminate;

        public DeleteEliminateCommandHandler(IBaseRepository<Eliminate> eliminate)
        {
            this.eliminate = eliminate;
        }

        public async Task<ApiResult<int>> Handle(DeleteEliminateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            try
            {
                var eliminateRecord = eliminate.GetAll().Where(x=>x.EliminateId == request.EliminateId).FirstOrDefault();

                if (eliminateRecord == null)
                {
                    res.Message = "淘汰记录不存在";
                    res.Code = ApiEnum.删除失败;
                    return res;
                }

                eliminateRecord.IsDeleted = true;

                var r = await eliminate.UpdateAsync(eliminateRecord);

                if (r > 0)
                {
                    res.Message = "删除成功";
                    res.Code = ApiEnum.删除成功;
                    res.data = r;
                }
                else
                {
                    res.Message = "删除失败";
                    res.Code = ApiEnum.删除失败;
                }
            }
            catch (Exception ex)
            {
                res.Message = "删除失败: " + ex.Message;
                res.Code = ApiEnum.删除失败;
            }

            return res;
        }
    }
}
